package org.rainbow.auth;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyRealm extends AuthorizingRealm {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		
		logger.debug("myrealm授权 前  doGetAuthorizationInfo。。。。。。。。。。。。。");
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.addRole("role3");
		authorizationInfo.addRole("role2");
		
		authorizationInfo.addObjectPermission(new BitPermission("+user+10"));
		authorizationInfo.addObjectPermission(new WildcardPermission("order:*"));
		
		authorizationInfo.addStringPermission("+goods+10");
		authorizationInfo.addStringPermission("shop:*");
		
		logger.debug("myrealm授权 后  doGetAuthorizationInfo。。。。。。。。。。。。。");
		
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		logger.debug("myrealm验证  doGetAuthenticationInfo。。。。。。。。。。。。。");
		
		String username = (String)token.getPrincipal(); //得到用户名
		String password = new String((char[])token.getCredentials()); //得到密码
		if(!"rainbow".equals(username)) {
			throw new UnknownAccountException(); //如果用户名错误
		}
		if(!"123456".equals(password)) {
			throw new IncorrectCredentialsException(); //如果密码错误
		}
		//如果身份认证验证成功，返回一个 AuthenticationInfo 实现；
		return new SimpleAuthenticationInfo(username, password, getName());
	}

}
